package com.xindaoapp.happypet.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.rockerhieu.emojicon.EmojiconHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PrivateMessageInfo;
import com.xindaoapp.happypet.bean.SendPrivateLetterReturnResult;
import com.xindaoapp.happypet.ui.BaseActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 私信
 * 
 * @author chenghao
 * 
 */
public class PrivateLetterActivity extends BaseActivity {
    private String mUserName;
    private ListView mListView;
    private EditText mETContent;
    private View mNoData;
    private PrivateMessageAdapter mAdapter;

    private List<PrivateMessageInfo> mList;

    private String mPostContent = "";
    private ImageView iv_left;
    private TextView iv_send;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

    }


    @Override
    protected int getContentViewResId() {
        return R.layout.layout_private_letter;
    }



    @Override
    protected void onLoadDatas() {
        // TODO Auto-generated method stub
        super.onLoadDatas();
        onload(new IRequest<Boolean>() {

            @Override
            public void request(Boolean t) {
                if (t) {
                    mListView.setSelection(mListView.getAdapter().getCount() - 1);
                }
            }
        });
    }


    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }


    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        // TODO Auto-generated method stub
        return getIntent().getStringExtra(Constants.KEY_USERNAME);
    }


    @Override
    protected void initViews() {
        super.initViews();
        mUserName = getIntent().getStringExtra(Constants.KEY_USERNAME);

        mList = new ArrayList<PrivateMessageInfo>();

        mNoData = findViewById(R.id.no_data_pl);
        mListView = (ListView) findViewById(R.id.listview);
        mETContent = (EditText) findViewById(R.id.content);
        l_bottom = (LinearLayout) findViewById(R.id.l_bottom);
        mETContent.addTextChangedListener(mContentTextWatcher);
        iv_send = (TextView) this.findViewById(R.id.iv_send);
        iv_left = (ImageView) this.findViewById(R.id.iv_left);

        mAdapter = new PrivateMessageAdapter(mList);
        mListView.setAdapter(mAdapter);



        // mETContent.setOnEditorActionListener(new OnEditorActionListener() {
        //
        // @Override
        // public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
        //
        // if (!TextUtils.isEmpty(mPostContent)) {
        // hideInputMethod();
        // sendMessage(mPostContent);
        // mETContent.setText("");
        // return true;
        // }
        // }
        // return false;
        // }
        // });

        iv_send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                if (!TextUtils.isEmpty(mPostContent)) {
                    hideInputMethod();
                    sendMessage(mPostContent);
                    mETContent.setText("");
                } else {
                    Toast.makeText(PrivateLetterActivity.this, "发送内容不能为空!", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });



        mListView.setOnItemLongClickListener(mItemLongClickListener);
    }

    private final TextWatcher mContentTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString())) {
                mPostContent = "";
                return;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

        @Override
        public void afterTextChanged(Editable arg0) {
            mPostContent = EmojiconHandler.getMEmojiCode();
        }

    };

    // 右边 屏蔽他人私信 暂时不用
    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            // openOptionsMenu();
            LayoutInflater inflater = LayoutInflater.from(getBaseContext());
            // 引入窗口配置文件
            View view = inflater.inflate(R.layout.popupwindow, null);
            final PopupWindow pop =
                    new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                            false);
            // 设置点击窗口外边窗口消失
            pop.setOutsideTouchable(true);
            pop.setBackgroundDrawable(new BitmapDrawable());
            // 设置此参数获得焦点，否则无法点击
            pop.setFocusable(true);
            pop.update();
            pop.showAtLocation(PrivateLetterActivity.this.findViewById(R.id.privatrmain),
                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            view.findViewById(R.id.private_ignol).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ignoreUser();
                    pop.dismiss();
                }
            });
            view.findViewById(R.id.private_cancle).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    pop.dismiss();
                }
            });



        }
    };

    private final OnItemLongClickListener mItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            showDeleteMessageDialog(((PrivateMessageInfo) parent.getAdapter().getItem(position)));
            return false;
        }
    };
    private LinearLayout l_bottom;

    private void showDeleteMessageDialog(final PrivateMessageInfo info) {
        new AlertDialog.Builder(this).setTitle("私信消息记录").setMessage("确认删除？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {}
                }).setPositiveButton("确认", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteMessage(info);
                    }
                }).create().show();
    }

    private void deleteMessage(final PrivateMessageInfo info) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .deletePrivateMessage(getIntent().getStringExtra(Constants.KEY_TOUID), info.pmid,
                        new IRequest<Pair<Boolean, String>>() {

                            @Override
                            public void request(Pair<Boolean, String> t) {
                                if (t != null) {
                                    if (t.first) {
                                        Toast.makeText(getBaseContext(), t.second,
                                                Toast.LENGTH_SHORT).show();

                                        mList.remove(info);
                                        mAdapter.resetList(mList);
                                        mAdapter.notifyDataSetChanged();
                                        if (mList.size() == 0) {
                                            mNoData.setVisibility(View.VISIBLE);
                                        } else {
                                            mListView.setSelection(mListView.getAdapter()
                                                    .getCount() - 1);
                                        }

                                        // onload(new IRequest<Boolean>() {
                                        //
                                        // @Override
                                        // public void request(Boolean t) {
                                        // mListView.setSelection(mListView.getAdapter()
                                        // .getCount() - 1);
                                        // }
                                        // });
                                    } else {
                                        Toast.makeText(getBaseContext(), t.second,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(getBaseContext(), R.string.net_error,
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
    }

    private void hideInputMethod() {
        InputMethodManager inputManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(mETContent.getWindowToken(), 0);
    }

    private void showInputMethod2() {
        InputMethodManager inputManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInputFromInputMethod(mETContent.getWindowToken(), 0);
    }

    private void sendMessage(final String message) {
        final ProgressDialog progressDialog =
                new ProgressDialog(PrivateLetterActivity.this, R.style.dialog_for_privateletter);
        progressDialog.setMessage(" 发送中,请稍后 ... ");
        progressDialog.show();
        HappyPetApplication
                .get()
                .getMoccaApi()
                .sendPrivateMessage(mUserName, message,
                        new IRequest<SendPrivateLetterReturnResult>() {

                            @Override
                            public void request(SendPrivateLetterReturnResult t) {
                                progressDialog.dismiss();
                                if (t != null) {
                                    if (t.getResult().equals("0")) {
                                        PrivateMessageInfo info = new PrivateMessageInfo();
                                        mNoData.setVisibility(View.GONE);
                                        SimpleDateFormat df =
                                                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        info.addtime =
                                                df.format(new Date(System.currentTimeMillis()));
                                        info.message = message;
                                        info.authorid = UserState.getUserUid();
                                        info.userface = UserState.getUser().userface;
                                        info.pmid = t.getPmid();
                                        mList.add(info);
                                        mAdapter.resetList(mList);
                                        mAdapter.notifyDataSetChanged();
                                        mListView
                                                .setSelection(mListView.getAdapter().getCount() - 1);
                                        Toast.makeText(getBaseContext(), t.getMsg(),
                                                Toast.LENGTH_SHORT).show();

                                        // onLoadDatas();
                                        // onload(new IRequest<Boolean>() {
                                        //
                                        // @Override
                                        // public void request(Boolean t) {
                                        // mListView
                                        // .setSelection(mListView.getAdapter().getCount() - 1);
                                        // }
                                        // });

                                    } else {
                                        Toast.makeText(getBaseContext(), t.getMsg(),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(getBaseContext(), R.string.net_error,
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
    }

    private void onload() {
        onload(null);
    }

    private void onload(final IRequest<Boolean> iRequest) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPrivateMessageListWithUid(getIntent().getStringExtra(Constants.KEY_TOUID),
                        new IRequest<List<PrivateMessageInfo>>() {

                            @Override
                            public void request(List<PrivateMessageInfo> t) {
                                if (null != t) {
                                    onDataArrived(true);
                                    if (t.size() == 0) {

                                        mNoData.setVisibility(View.VISIBLE);
                                    } else {
                                        mList = t;
                                        mNoData.setVisibility(View.GONE);
                                        // if (mAdapter == null) {
                                        // // mAdapter = new PrivateMessageAdapter(mList);
                                        // mListView.setAdapter(mAdapter);
                                        // } else {
                                        mAdapter.resetList(mList);
                                        mAdapter.notifyDataSetChanged();
                                        // }
                                        if (null != iRequest) {
                                            iRequest.request(true);
                                        }
                                    }
                                } else {
                                    if (null != iRequest) {
                                        iRequest.request(false);
                                    }
                                    onDataArrived(false);

                                }
                            }
                        });
    }

    /**
     * // 忽略本人消息 暂时不用
     */

    // @Override
    // public boolean onCreateOptionsMenu(Menu menu) {
    // menu.add(0, Menu.FIRST, 0, "取消");
    // menu.add(0, Menu.FIRST + 1, 0, "忽略");
    // return super.onCreateOptionsMenu(menu);
    // }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case 1:
                break;
            case 2:
                ignoreUser();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void ignoreUser() {
        HappyPetApplication.get().getMoccaApi()
                .ignorePrivateMessageWithUid(mUserName, new IRequest<Pair<Boolean, String>>() {

                    @Override
                    public void request(Pair<Boolean, String> t) {
                        if (t != null) {
                            if (t.first) {
                                Toast.makeText(getBaseContext(), t.second, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                Toast.makeText(getBaseContext(), t.second, Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } else {
                            Toast.makeText(getBaseContext(), R.string.net_error, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    class PrivateMessageAdapter extends BaseAdapter {
        private List<PrivateMessageInfo> list;

        private final int CHAT_TYPE_LEFT = 0;
        private final int CHAT_TYPE_RIGHT = 1;

        public PrivateMessageAdapter(List<PrivateMessageInfo> list) {
            super();
            this.list = list;
        }

        public void resetList(List<PrivateMessageInfo> t) {
            this.list = t;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public PrivateMessageInfo getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public int getItemViewType(int position) {
            if (getItem(position).authorid.equals(UserState.getUserUid())) {
                return CHAT_TYPE_RIGHT;
            } else {
                return CHAT_TYPE_LEFT;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            PrivateMessageInfo info = list.get(position);
            if (getItemViewType(position) == CHAT_TYPE_LEFT) {
                if (convertView == null) {
                    convertView =
                            View.inflate(getBaseContext(), R.layout.item_private_message_left, null);
                }
            } else if (getItemViewType(position) == CHAT_TYPE_RIGHT) {
                if (convertView == null) {
                    convertView =
                            View.inflate(getBaseContext(), R.layout.item_private_message_right,
                                    null);
                }
            }
            setViews(convertView, info);
            return convertView;
        }

        private void setViews(View convertView, PrivateMessageInfo info) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (CircleImageView) convertView.findViewById(R.id.icon);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                convertView.setTag(holder);
            }
            ImageLoader.getInstance().displayImage(info.userface, holder.icon);
            SpannableStringBuilder ssb =
                    CommonUtil.convetToHtml(CommonUtil.parseEmoji(info.message),
                            PrivateLetterActivity.this);
            holder.content.setText(ssb);
            holder.time.setText(CommonUtil.formatTime(info.addtime));
        }

        class ViewHolder {
            CircleImageView icon;
            TextView content;
            TextView time;
        }

    }



}
